package com.cloudbroker.bcs.common.mq.spring.converter;

import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import com.alibaba.fastjson.JSON;
import com.cloudbroker.bcs.common.util.IOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;

public class FastjsonMessageConverter extends AbstractMessageConverter {
    
    public static final Charset DEFAULT_CHARSET = IOUtil.CHARSET_UTF8;
    
    private Charset defaultCharset = DEFAULT_CHARSET;
    
    @Override
    protected Message createMessage(Object object, MessageProperties messageProperties) {
        String jsonString = JSON.toJSONString(object);
        byte[] bytes = jsonString.getBytes(defaultCharset);
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(getDefaultCharset());
        messageProperties.setContentLength(bytes.length);
        return new Message(bytes, messageProperties);
    }
    
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        byte[] bytes = message.getBody();
        MessageProperties messageProperties = message.getMessageProperties();
        if (null != messageProperties) {
            String contentType = ValueUtil.getString(messageProperties.getContentType());
            if (contentType.startsWith(MessageProperties.CONTENT_TYPE_JSON)) {
                Charset charset = null;
                String contentEncoding = ValueUtil.getString(messageProperties.getContentEncoding());
                if (StringUtils.isNotBlank(contentEncoding)) {
                    charset = Charset.forName(contentEncoding);
                } else {
                    charset = defaultCharset;
                }
                
                String text = new String(bytes, charset);
                return JSON.parseObject(text);
            }
        }
        return bytes;
    }
    
    public String getDefaultCharset() {
        return defaultCharset.name();
    }
    
    public void setDefaultCharset(String defaultCharset) {
        if (null != defaultCharset) {
            this.defaultCharset = Charset.forName(defaultCharset);
        }
    }
    
}
